﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NPC : MonoBehaviour
{
    Animator am;
    float moveTime;
    bool moveLeft;

    public int hp = 2;
    public float speed = 1;
    public LayerMask BG;
    public LayerMask player;
    void Start()
    {
        am = GetComponent<Animator>();

        // 添加死亡动画的帧事件
        foreach (var item in am.runtimeAnimatorController.animationClips)
        {
            if (item.name.Equals("NPC_Die"))
            {
                AnimationEvent ae = new AnimationEvent();
                ae.time = item.length;
                ae.functionName = "NpcDie";
                item.AddEvent(ae);
            }

            if (item.name.Equals("NPC_Hurt"))
            {
                AnimationEvent ae = new AnimationEvent();
                ae.time = item.length;
                ae.functionName = "NpcHurt";
                item.AddEvent(ae);
            }
        }
    }


    void Update()
    {
        // 人物是否进入攻击范围
        Debug.DrawRay(transform.position, transform.right);
        if (Physics2D.Raycast(transform.position, transform.right, 0.7F, player))
        {
            am.SetBool("attack", true);
            am.SetBool("run", false);
        }
        else // 不在攻击范围 巡逻
        {
            am.SetBool("attack", false);

            // 按照是否有地形巡逻
            if (Physics2D.Raycast(transform.position, Vector2.down, 1, BG))
            {
                am.SetBool("run", true);
                #region 按照时间巡逻
                //speed *= -1;
                //moveTime += Time.deltaTime;
                //if (moveTime > 1)
                //{
                //    transform.localScale = new Vector3(transform.localScale.x*-1, transform.localScale.y, transform.localScale.z);
                //    speed *= -1;
                //    moveTime = 0;
                //} 
                #endregion
            }
            else
            {
                speed *= -1;
                //transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);// 缩放扭头
                transform.Rotate(new Vector3(0, 180, 0)); // 旋转扭头
            }
            transform.Translate(transform.right * speed * Time.deltaTime);
        }
    }


    
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "PlayerButter")
        {
            am.SetBool("hurt", true);

            if (--hp <= 0)
            {
                am.SetBool("die", true);
                am.SetBool("run", false);
                am.SetBool("attack", false);
                am.SetBool("hurt", false);
            }
        }
    }



    // 死亡帧事件
    void NpcDie()
    {
        if (hp <= 0)
        {
            Destroy(gameObject);
        }
    }

    // 受伤帧事件
    void NpcHurt()
    {
        am.SetBool("hurt", false);
    }

}
